//
//  YSCategorieCtrl.m
//  Yueshi
//
//  Created by Northwan on 15/9/7.
//  Copyright (c) 2015年 悦食中国. All rights reserved.
//  分类

#import "YSCategorieCtrl.h"
#import "YSCategoryItemCell.h"
#import "YSCategoryDataTool.h"
#import "YSCategoryHeaderView.h"
#import "YSProductListCtrl.h"
#import "CartView.h"
#import "YSSearchNoResultView.h"
#import "SearchHistoryDao.h"
#import "YSProductListGridItemCell.h"
#import "YSProductDetailCtrl.h"
#import "YSVipCategorieCtrl.h"

#define kSearchBarWidth (SCREENW-90)
#define kSearchBarViewWidth (SCREENW-16)

@interface YSCategorieCtrl ()<UICollectionViewDataSource,UICollectionViewDelegate,UISearchBarDelegate,UITableViewDataSource,UITableViewDelegate>
@property (nonatomic,weak)UICollectionView *collectionView;
@property (nonatomic,strong)NSMutableArray *itemArray;
@property (nonatomic,strong)YSCategoryRes *result;
@property (nonatomic,strong)CartView *cartView;

@property (nonatomic,strong)UITableView *searchTableView;
@property (nonatomic,strong)UISearchBar *searchBar;
@property (nonatomic,strong)UIView *searchBarView;
@property (nonatomic,strong)YSSearchNoResultView *searchNoResult;
@property (nonatomic,strong)UIView *searchView;
@property (nonatomic,assign)float showHeight;
@property (nonatomic,strong)NSMutableArray *searchHistoryArray;
@property (nonatomic,strong)SearchHistoryDao *searchDao;
@property (nonatomic,assign)BOOL isShowFooter;

@property(nonatomic,strong) UICollectionView *searchCollectionView;
@property(nonatomic,assign) NSInteger pageIndex;
@property(nonatomic,strong) NSMutableArray *searchProdArray;
@end

@implementation YSCategorieCtrl

-(NSMutableArray *)itemArray{
    if(!_itemArray){
        _itemArray =  [NSMutableArray array];
    }
    return _itemArray;
}

-(NSMutableArray *)searchProdArray{
    if(!_searchProdArray){
        _searchProdArray =  [NSMutableArray array];
    }
    return _searchProdArray;
}

static NSString * const categotyReuseIdentifier = @"YSCategoryItemCell";
static NSString * const productReuseIdentifier = @"YSProductListItemCell";

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setTitle:@"分类"];
    
    /*
    _searchDao = [[SearchHistoryDao alloc]init];
    _isShowFooter = YES;
    
    _showHeight =   SCREENH-NavWithStatusBarH-49;
    
    _searchView = [[UIView alloc]init];
    _searchView.hidden = YES;
    [_searchView setBackgroundColor:[UIColor clearColor]];
    [self.view addSubview:_searchView];
    
    _searchView.frame = CGRectMake(0, 0, SCREENW, SCREENH-NavWithStatusBarH-49);
    */
    
    [self initCollectionView];
    [self.collectionView.header beginRefreshing];
    
    //初始化搜索view
//    [self initSearchView];
}

-(void)initTitleItem{
    CartView *cartView = [[CartView alloc]initWithImage:@"btn_cart"];
    [cartView addTarget:self action:@selector(tapTitleRightItem:) forControlEvents:UIControlEventTouchUpInside];
    _cartView = cartView;
    
    self.navigationItem.rightBarButtonItem =  [[UIBarButtonItem alloc]initWithCustomView:_cartView];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:_cartView];
}

-(void)initSearchCollectionView{
    UICollectionViewFlowLayout *flowLayout =[[UICollectionViewFlowLayout alloc]init];
    [flowLayout setMinimumLineSpacing:5];
    [flowLayout setMinimumInteritemSpacing:5];
    
    UICollectionView *collectionView  =[[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, SCREENW, _showHeight) collectionViewLayout:flowLayout];
    [collectionView setBackgroundColor:HEXColor(@"#eaeae9")];
    [collectionView registerClass:[YSProductListGridItemCell class] forCellWithReuseIdentifier:productReuseIdentifier];
    
    [collectionView setDelegate:self];
    [collectionView setDataSource:self];
    [collectionView setAlwaysBounceVertical:YES];
    [collectionView registerNib:[UINib nibWithNibName:productReuseIdentifier bundle: [NSBundle mainBundle]] forCellWithReuseIdentifier:productReuseIdentifier];
    [_searchView addSubview:collectionView];
    [collectionView setHidden:YES];
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(searchHeaderRefresh)];
    header.lastUpdatedTimeLabel.hidden = YES;
    collectionView.header = header;
    collectionView.footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(searchFooterRefresh)];
    self.searchCollectionView = collectionView;
}

-(void)searchHeaderRefresh{
    self.pageIndex = 0;
    [self requestSearchDataWithKeyWords:_searchBar.text];
}

-(void)searchFooterRefresh{
    self.pageIndex ++;
    [self requestSearchDataWithKeyWords:_searchBar.text];
}

-(void)initSearchView{
    //添加搜索
    UISearchBar *searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, kSearchBarWidth, 30)];
    [searchBar setSearchFieldBackgroundImage:[UIImage imageNamed:@"searchbar_textfield_background"] forState:UIControlStateNormal];
    searchBar.delegate = self;
    searchBar.placeholder = @"搜索";
    [searchBar setBackgroundColor:[UIColor clearColor]];
    [searchBar setBarTintColor:[UIColor whiteColor]];
    [searchBar setKeyboardType:UIKeyboardTypeDefault];
    [searchBar setTintColor:ThemeColor];
    [searchBar setValue:@(0) forKeyPath:@"_background.alpha"];
    _searchBar = searchBar;
    
    if (iOS8) {
        self.navigationItem.titleView = _searchBar;
    }else{
        _searchBarView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kSearchBarViewWidth, 30)];
        [_searchBarView addSubview:_searchBar];
        self.navigationItem.titleView = _searchBarView;
    }
    
    UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREENW, _showHeight) style:UITableViewStyleGrouped];
    [tableView setBackgroundColor:HEXColor(@"#eaeae9")];
    [tableView setSectionFooterHeight:30];
    
    UIView *header = [UIView new];
    [header setFrame:CGRectMake(0, 0, SCREENW, 0.1)];
    [tableView setTableHeaderView:header];
    [tableView setSeparatorColor:HEXColor(@"#d4d4d4")];
    [tableView setDelegate:self];
    [tableView setDataSource:self];
    
    UIView *footerView = [UIView new];
    [footerView setBackgroundColor:[UIColor clearColor]];
    [tableView setTableFooterView:footerView];
    [_searchView addSubview:tableView];
    _searchTableView = tableView;
    
    [self initSearchCollectionView];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
   
    if(!_searchView.hidden){
        [_searchBar becomeFirstResponder];
    }
    [self initTitleItem];
    if(_cartView){
        NSInteger num =  [DefaultsHelper integerForKey:kCartIndex];
        [_cartView setNum:num];
    }
}

-(void)tapTitleRightItem:(UIBarButtonItem *)btnItem{
    [Utils showCartCtrl:self];
}

-(void)requestData{
    [YSCategoryDataTool getCategoryInfo:^(YSCategoryRes *result) {
        [self.collectionView.header endRefreshing];
        if(result.isSucc){
            _result = result;
            [_itemArray removeAllObjects];
            [_itemArray addObjectsFromArray:result.productCategory];
            
            [self.collectionView reloadData];
        }else{
            ShowEnterTips(result.data);
        }
    } failure:^(NSError *error) {
        [self.collectionView.header endRefreshing];
        ShowTips(kRequestFailure)
    }];
}

-(void)initCollectionView{
    UICollectionViewFlowLayout *flowLayout =[[UICollectionViewFlowLayout alloc]init];
    [flowLayout setMinimumLineSpacing:5];
    [flowLayout setMinimumInteritemSpacing:5];
    
    UICollectionView *collectionView  =[[UICollectionView alloc]initWithFrame:    CGRectMake(0, 0, SCREENW, SCREENH) collectionViewLayout:flowLayout];
    collectionView.height = collectionView.height-BottomTabarH-NavWithStatusBarH;
    [collectionView setBackgroundColor:PUBLIC_BG];
    [collectionView registerClass:[YSCategoryItemCell class] forCellWithReuseIdentifier:@"collectionView"];
    //添加头
    [collectionView  registerClass:[YSCategoryHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"head"];
    
    [collectionView setDelegate:self];
    [collectionView setDataSource:self];
    [collectionView setAlwaysBounceVertical:YES];
    [collectionView registerNib:[UINib nibWithNibName:categotyReuseIdentifier bundle: [NSBundle mainBundle]] forCellWithReuseIdentifier:categotyReuseIdentifier];
    [self.view addSubview:collectionView];
    
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefresh)];
    header.lastUpdatedTimeLabel.hidden = YES;
    collectionView.header = header;
    self.collectionView = collectionView;
}

-(void)headerRefresh{
    [self requestData];
}

#pragma mark <UICollectionViewDataSource>
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if(collectionView == _collectionView){
        return self.itemArray.count;
    }else{
        return self.searchProdArray.count;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
     if(collectionView == _collectionView){
         YSCategoryItemCell *cell = [YSCategoryItemCell cellWithCollectionView:collectionView indexPath:indexPath];
         [cell setCategory:self.itemArray[indexPath.row]];
         return cell;
     }else{
         YSProductListGridItemCell *cell = [YSProductListGridItemCell cellWithCollectionView:collectionView indexPath:indexPath];
         [cell setProd:self.searchProdArray[indexPath.row]];
         return cell;
     }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    if(collectionView ==_collectionView){
        return CGSizeMake((SCREENW-5)/2, 125);
    }else{
        return CGSizeMake((SCREENW-25)/2, 250);
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"indexpath.row=%ld",(long)indexPath.row);
    if(collectionView == _collectionView){
        YSProductCategory *category =  _itemArray[indexPath.row];
        [TalkingData trackEvent:[NSString stringWithFormat:@"%ld",category.categoryId]];
        if (category.categoryId == 54){//vip定制
            if (ISLOGIN) {
                 [self.navigationController pushViewController:[[YSVipCategorieCtrl alloc] init] animated:YES];
            }else{
                [Utils showLoginCtrl:self];
            }
        }else{
            [self.navigationController pushViewController:[[YSProductListCtrl alloc]initWithTitle:category.categoryName categoryId:category.categoryId type:CATEGORY_TYPE] animated:YES];
        }
    }else{
        NSInteger prodId = [self.searchProdArray[indexPath.row] prodId];
        YSProductDetailCtrl *ctrl =  [[YSProductDetailCtrl alloc]initWithProdId:prodId];
        [self.navigationController pushViewController:ctrl animated:YES];
    }
}

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    if(collectionView == _collectionView){
        return UIEdgeInsetsMake(5, 0, 5, 0);
    }else{
        return UIEdgeInsetsMake(10,10,10,10);
    }
}

//这个是返回顶部广告的view
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if(collectionView ==_collectionView){
        YSCategoryHeaderView *head = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"head" forIndexPath:indexPath];
        if(_result.bannerList){
            [head setBanner:_result.bannerList];
        }
        return head;
    }
    return nil;
}

//这个是返回顶部广告的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
     if(collectionView ==_collectionView){
         if(_result.bannerList){
             return CGSizeMake(SCREENW, SCREENW/1.5);
         }
     }
    return CGSizeZero;
}

-(void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    if ([_searchTableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [_searchTableView setSeparatorInset:UIEdgeInsetsMake(0,YSPublicXInset,0,0)];
    }
    
    if ([_searchTableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [_searchTableView setLayoutMargins:UIEdgeInsetsMake(0,YSPublicXInset,0,0)];
    }
}

#pragma mark - searchbar代理方法
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
    [_searchTableView setHidden:NO];
    [_searchNoResult setHidden:YES];
    searchBar.placeholder = @"请输入商品名称";
    _searchHistoryArray = [NSMutableArray arrayWithArray:[_searchDao selectAllData]];
    [_searchTableView reloadData];
    [searchBar setShowsCancelButton:YES animated:NO];
    
    for(UIView *view in  [[[searchBar subviews] objectAtIndex:0] subviews]) {
        if([view isKindOfClass:[NSClassFromString(@"UINavigationButton") class]]) {
            UIButton * cancel =(UIButton *)view;
            [cancel.titleLabel setFont:SYS_FONT(15)];
            [cancel setTitle:@"取消" forState:UIControlStateNormal];
            [cancel setTitleColor:ThemeColor forState:UIControlStateNormal];
            self.navigationItem.rightBarButtonItem = nil;
            self.navigationItem.leftBarButtonItem = nil;
        }
    }
    
    if (iOS7) {
        searchBar.width = kSearchBarViewWidth;
    }
    
    _collectionView.hidden = YES;
    _searchView.hidden = NO;

    return true;
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    _isShowFooter = YES;
    searchBar.placeholder = @"搜索";
    [searchBar resignFirstResponder];
    [searchBar setText:@""];
    [searchBar setShowsCancelButton:NO animated:YES];
    _collectionView.hidden = NO;
    _searchView.hidden = YES;
    
    if (iOS7) {
        searchBar.width = kSearchBarWidth;
    }
    
    self.navigationItem.rightBarButtonItem =  [[UIBarButtonItem alloc]initWithCustomView:_cartView];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:_cartView];
    
    [_searchProdArray removeAllObjects];
    [_searchCollectionView reloadData];
    _searchCollectionView.hidden = YES;
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    _pageIndex = 0;
    [self requestSearchDataWithKeyWords:searchBar.text];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    _isShowFooter = NO;
    if(ISBLANK(searchText)) return;
    [YSCategoryDataTool searchThinkKeysWithParam:searchText success:^(SearchThinkKeys *result) {
        NSLog(@"返回结果：%@",result.thinkKeys);
        if(result.thinkKeys){
            [_searchHistoryArray removeAllObjects];
            [_searchHistoryArray addObjectsFromArray:result.thinkKeys];
            [_searchTableView reloadData];
        }
    } failure:^(NSError *error) {
        
    }];
}

#pragma mark - TableView 代理方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if(_isShowFooter){
        return 2;
    }
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if(section){
        if(_searchHistoryArray.count){
            return 1;
        }
    }else{
        return _searchHistoryArray.count;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    // 0.用static修饰的局部变量，只会初始化一次
    static NSString *ID = @"cell";
    // 1.拿到一个标识先去缓存池中查找对应的Cell
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
   
    // 2.如果缓存池中没有，才需要传入一个标识创建新的Cell
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    }
    [cell setBackgroundColor:HEXColor(@"#eaeae9")];
    if(!indexPath.section){
        cell.imageView.image = [UIImage imageNamed:@"search_history_icon"];
        cell.textLabel.textColor = publicTextColor;
        cell.textLabel.textAlignment = NSTextAlignmentLeft;
        cell.textLabel.text = _searchHistoryArray[indexPath.row];
        return cell;
    }else{
        cell.imageView.image = nil;
        cell.textLabel.textColor = publicTextColor;
        cell.textLabel.textAlignment = NSTextAlignmentCenter;
        cell.textLabel.text = @"清除历史记录";
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section){
        //点击了清除历史记录
        [_searchDao deleteAllHistory];
        [_searchHistoryArray removeAllObjects];
        [tableView reloadData];
    }else{
        //点击了条目，这个地方去请求数据
        
        [self requestSearchDataWithKeyWords:_searchHistoryArray[indexPath.row]];
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - 请求搜索数据
-(void)requestSearchDataWithKeyWords:(NSString *)keyWords{
    _searchTableView.hidden = YES;
    _searchCollectionView.hidden = NO;
    if(ISBLANK(keyWords)) return;
    [_searchDao addKeyWords:keyWords];
    self.searchBar.text = keyWords;
    [YSCategoryDataTool searchProductDataWithKeyWords:keyWords pageIndex:_pageIndex success:^(ProductSearch *result) {
        [self searchCollectionViewComplete];
        if (result.isSucc) {
            [_searchNoResult setHidden:YES];
            if(_pageIndex == 0){
                [_searchProdArray removeAllObjects];
            }
            [_searchProdArray addObjectsFromArray:result.productList];
            [_searchCollectionView reloadData];
            [self hideKeyWordsWithHideCancle];
            
            if(!_searchProdArray.count){
                [self showNullResultView];
            }
        }else{
             _searchCollectionView.hidden = YES;
            [self hideKeyWordsWithHideCancle];
        }
    } failure:^(NSError *error) {
         _searchCollectionView.hidden = YES;
        [self searchCollectionViewComplete];
        [self hideKeyWordsWithHideCancle];
    }];

}

-(void)searchCollectionViewComplete{
    if(_searchCollectionView){
        [_searchCollectionView.header endRefreshing];
        [_searchCollectionView.footer endRefreshing];
    }
}

#pragma mark -注销第一响应者，并且隐藏取消
-(void)hideKeyWordsWithHideCancle{
    [_searchBar resignFirstResponder];
    [_searchBar setShowsCancelButton:NO animated:YES];
}

/**
 *  显示末搜索到结果的页面
 */
-(void)showNullResultView{
    if (_searchNoResult==nil) {
        _searchNoResult = [[YSSearchNoResultView alloc]init];
        _searchNoResult.x = (_searchView.width-_searchNoResult.width)/2;
        _searchNoResult.y = (_searchView.height-_searchNoResult.height)/2;
        [_searchView addSubview:_searchNoResult];
        _searchNoResult.hidden = YES;
    }
    _searchTableView.hidden = YES;
    _searchNoResult.hidden = NO;
    _searchCollectionView.hidden = YES;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if([scrollView isKindOfClass:[UITableView class]]){
        [self hideKeyWordsWithHideCancle];
    }
    if(!self.searchView.hidden){
        [self hideKeyWordsWithHideCancle];
    }
}

@end